// Copyright (c) [2021] [daifang]
// [Dcomponent] is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of Mulan PSL v2 at:
//          http://license.coscl.org.cn/MulanPSL2
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
// MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
// See the Mulan PSL v2 for more details.
import {useEffect, useState, useContext} from 'react'
import { bool, func, number, object, string } from 'prop-types';
import { Context, FieldContext } from '../index'

export default function Input(props) {
    let {type, defalutValue, onChange, maxLength, disable, width, height, placeholder} = props
    const [value, setValue] = useState(defalutValue||'')
    const {formData, setFormData} = useContext(Context)
    const {setItemVal, name, isPass} = useContext(FieldContext)
    useEffect(() => {
        // console.log(index,'didT')
        if(formData[name]) formData[name].value = value
        if(setItemVal) setItemVal(value)
        // console.log(formData[name], 'did')
        setFormData(formData)
        // setFormData(formData)
        return () => {

        }
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [value])
    return (
        <div className={`d-input ${isPass?'':'inputError'}`} style={{width:`${width}px`,height:`${height}px`}}>
            <input
                value={value} 
                type={type}
                readOnly={disable}
                maxLength={maxLength}
                placeholder={placeholder}
                onInput={(e)=>{
                    let val = e.target.value
                    setValue(val)
                    if(onChange){
                        onChange(val)
                    } 
                }}
            />
        </div>
    )
}

Input.propTypes = {
    onChange:func,
    maxLength:number,
    checkRules:object,
    placeholder:string,
    defalutValue:string,
    disable:bool,
    type:string
}